import 'package:get/get.dart';
import 'package:share_fit/app/controllers/base/base_sports_controller.dart';
import 'package:share_fit/app/controllers/home/exercise_records/model/exercise_type.dart';
import 'package:share_fit/app/controllers/sports/sports_const.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/generated/locales.g.dart';

import 'state.dart';

class SportManagementLogic extends BaseSportsController {
  final SportManagementState state = SportManagementState();

  goBack({List<ExerciseType>? mySportList}) {
    Get.back(result: mySportList);
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathSports;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathSports;
  }

  @override
  void initState() {
    // List<ExerciseType> ets = read(SportsConst.mySportList, defaultValue: <ExerciseType>[], global: true);
    // if (ets.isEmpty) {
      state.mySportList = Get.arguments ?? [];
    // } else {
    //   state.mySportList = ets;
    // }

    initSportManagementInfo();
  }

  initSportManagementInfo() {
    Map map = read(SportsConst.sportsManagementMap, defaultValue: {});

    state.maxList = map['maxCount'] ?? state.maxList;
    state.minList = map['minCount'] ?? state.minList;

    Set<int> support = Set.from(map['supportsSportsList'] ?? []);
    support.removeWhere((type) => state.mySportList.any((element) => element.type.code == type));
    state.optionalList = support.map((type) {
      ExerciseType et = ExerciseType(Type.getType(type), '');
      if (et.type.code == -10) {
        print('unrecognized type : $type');
      }
      return et;
    }).toList();
  }

  @override
  void onRemoteEvent(event, method){
  }

  addToMySportList(ExerciseType exerciseType) {
    if (state.mySportList.length >= state.maxList) {
      showTips(LocaleKeys.info.ts, LocaleKeys.sports_max_items_text.ts.replaceFirst(RegExp('\\d'), state.maxList.toString()));
      return;
    }
    state.optionalList.remove(exerciseType);
    state.mySportList.add(exerciseType);
    update([SportsConst.mySportList, SportsConst.optionalSportList]);
  }

  removeFromMySportList(ExerciseType exerciseType) {
    if (state.mySportList.length == state.minList) {
      showTips(LocaleKeys.info.ts, LocaleKeys.sports_min_items_text.ts.replaceFirst(RegExp('\\d'), state.minList.toString()));
      return;
    }
    state.mySportList.remove(exerciseType);
    state.optionalList.insert(0, exerciseType);
    update([SportsConst.mySportList, SportsConst.optionalSportList]);
  }

  onSaveMySportList() {
    save(SportsConst.mySportList, state.mySportList);
    syncMySportListToDevice(state.mySportList);
    goBack(mySportList: state.mySportList);
  }
}
